package tinybase.rm;
import java.nio.ByteBuffer;

import junit.framework.Assert;
import tinybase.basic.RC;
import tinybase.pf.PageNum;
import tinybase.pf.Slot;

public class RID {
	
	public static final int RID_SIZE = 8;
	
	private int pageNum;
	private int slotNum; 

	public byte[] toBytes() {
		byte[] arr= new byte[RM_Internal.RM_RID_SIZE];
		ByteBuffer buf= ByteBuffer.wrap(arr);
		buf.putInt(0, this.pageNum);
		buf.putInt(4, this.slotNum);
		return arr;
	}
	
	public void setRID(RID rid) {
		this.pageNum= rid.pageNum;
		this.slotNum= rid.slotNum;
	}
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + pageNum;
		result = prime * result + slotNum;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		RID other = (RID) obj;
		if (pageNum != other.pageNum)
			return false;
		if (slotNum != other.slotNum)
			return false;
		return true;
	}

	public RID() {
		
	}
	
	public RID(int pageNum, int slotNum) {
		this.pageNum = pageNum;
		this.slotNum = slotNum;
	}
	
	//
	// getPageNum
	// 
	// Desc: Return page number
	// Out:  refPageNum - set to this RID's page number
	// Ret:  RC
	//
	public RC getPageNum(PageNum refPageNum) {
		if(this.pageNum == 0){
			return RC.RM_INVIABLERID;
		}
		
		refPageNum.setPageNum(this.pageNum);			
		
		return RC.SUCCESS;
	}

	//
	// GetSlotNum
	// 
	// Desc: Return slot number
	// Out:  refSlot - set to this RID's slot number
	// Ret:  RC
	//
	public RC getSlotNum(Slot refSlot) {
		if(this.pageNum == 0){
			return RC.RM_INVIABLERID;
		}
		Assert.assertTrue(refSlot != null);
		refSlot.setSlotValue(this.slotNum);
		return RC.SUCCESS;
	}
	
	public void setPageNum(int pageNum) {
		this.pageNum = pageNum;
	}

	public void setSlotNum(int slotNum) {
		this.slotNum = slotNum;
	}

	public void getFromBytes(byte[] arr) {
		ByteBuffer buf= ByteBuffer.wrap(arr);
		this.pageNum= buf.getInt(0);
		this.slotNum= buf.getInt(4);
	}

}
